// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV }) // 使用当前云环境

// 获取数据库引用
const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const { action, data } = event

  try {
    switch (action) {
      case 'save_calculation':
        return await saveCalculation(data, wxContext)
      case 'update_calculation':
        return await updateCalculation(data, wxContext)
      case 'get_calculation':
        return await getCalculation(data, wxContext)
      case 'search_calculation_by_name':
        return await searchCalculationByName(data, wxContext)
      case 'get_calculation_history':
        return await getCalculationHistory(data, wxContext)
      case 'clear_calculation_history':
        return await clearCalculationHistory(data, wxContext)
      case 'delete_calculation':
        return await deleteCalculation(data, wxContext)
      case 'filter_motors':
        return await filterMotors(data, wxContext)
      default:
        return {
          success: false,
          message: `未知的操作类型: ${action}`
        }
    }
  } catch (error) {
    console.error('云函数执行错误:', error)
    return {
      success: false,
      message: error.message || '服务器内部错误'
    }
  }
}

/**
 * 保存计算记录到数据库
 */
async function saveCalculation(data, wxContext) {
  try {
    // 数据验证
    if (!data) {
      throw new Error('数据不能为空')
    }

    // 构造要插入的数据
    const insertData = {
      // 基本信息
      openid: data.openid || wxContext.OPENID,
      createTime: data.createTime || new Date(),
      
      // 表单数据
      formData: data.formData || {},
      
      // 计算结果
      calcResults: data.calcResults || {},
      // 曲线图文件ID
      speedChartFileId: data.speedChartFileId || '',
      forceChartFileId: data.forceChartFileId || '',
      // 更新时间
      updateTime: new Date()
    }

    // 插入数据到 motor_calc_history 集合
    const result = await db.collection('motor_calc_history').add({
      data: insertData
    })

    return {
      success: true,
      message: '计算记录保存成功',
      recordId: result._id,
    }

  } catch (error) {
    return {
      success: false,
      message: error.message || '服务器内部错误'
    }
  }
}

/**
 * 更新计算记录到数据库
 */
async function updateCalculation(data, wxContext) {
  try {
    // 数据验证
    if (!data) {
      throw new Error('数据不能为空')
    }

    if (!data.recordId) {
      throw new Error('记录ID不能为空')
    }

    // 首先查询记录是否存在，并验证权限
    const queryResult = await db.collection('motor_calc_history')
      .doc(data.recordId)
      .get()

    if (!queryResult.data) {
      throw new Error('记录不存在')
    }

    // 验证用户权限（只有记录创建者才能更新）
    const currentUser = data.openid || wxContext.OPENID
    if (queryResult.data.openid !== currentUser) {
      throw new Error('没有权限更新此记录')
    }

    // 构造要更新的数据（只包含要更新的字段）
    const updateData = {
      updateTime: new Date()
    }

    // 只更新提供的字段
    if (data.formData !== undefined) {
      updateData.formData = data.formData
    }
    
    if (data.calcResults !== undefined) {
      updateData.calcResults = data.calcResults
    }
    
    if (data.speedChartFileId !== undefined) {
      updateData.speedChartFileId = data.speedChartFileId
    }
    
    if (data.forceChartFileId !== undefined) {
      updateData.forceChartFileId = data.forceChartFileId
    }

    // 添加对选择电机的更新支持
    if (data.selectedMotor !== undefined) {
      updateData.selectedMotor = data.selectedMotor
    }

    // 添加对Excel文件ID的更新支持
    if (data.excelFileId !== undefined) {
      updateData.excelFileId = data.excelFileId
    }

    // 更新数据库记录
    const updateResult = await db.collection('motor_calc_history')
      .doc(data.recordId)
      .update({
        data: updateData
      })

    return {
      success: true,
      message: '计算记录更新成功',
      recordId: data.recordId,
      stats: updateResult.stats
    }

  } catch (error) {
    return {
      success: false,
      message: error.message || '服务器内部错误'
    }
  }
}

/**
 * 获取计算记录
 */
async function getCalculation(data, wxContext) {
  try {
    // 数据验证
    if (!data || !data.recordId) {
      throw new Error('记录ID不能为空')
    }

    // 查询记录
    const queryResult = await db.collection('motor_calc_history')
      .doc(data.recordId)
      .get()

    if (!queryResult.data) {
      throw new Error('记录不存在')
    }

    // 验证用户权限（只有记录创建者才能查看）
    // const currentUser = data.openid || wxContext.OPENID
    // if (queryResult.data.openid !== currentUser) {
    //   throw new Error('没有权限查看此记录')
    // }

    return {
      success: true,
      message: '获取记录成功',
      data: queryResult.data
    }

  } catch (error) {
    return {
      success: false,
      message: error.message || '服务器内部错误'
    }
  }
}

/**
 * 根据机器名和轴名搜索计算记录
 */
async function searchCalculationByName(data, wxContext) {
  try {
    // 数据验证
    if (!data || !data.machineName || !data.axisName) {
      throw new Error('机器名称和轴名称不能为空')
    }

    const currentUser = data.openid || wxContext.OPENID

    // 查询该用户的匹配记录，按创建时间倒序排列，取最新的一条
    const queryResult = await db.collection('motor_calc_history')
      .where({
        openid: currentUser,
        'formData.machineName': data.machineName,
        'formData.axisName': data.axisName
      })
      .orderBy('createTime', 'desc')
      .limit(1)
      .get()

    if (!queryResult.data || queryResult.data.length === 0) {
      return {
        success: false,
        message: '未找到匹配的计算记录',
        data: null
      }
    }

    const record = queryResult.data[0]

    return {
      success: true,
      message: '查询成功',
      data: record
    }

  } catch (error) {
    console.error('搜索计算记录失败:', error)
    return {
      success: false,
      message: error.message || '服务器内部错误'
    }
  }
}

async function filterMotors(data, wxContext) {
  if (!data) {
    return {
      success: false,
      message: '删选数据不能为空'
    }
  }

  if (!data.lowerContinuousForce || !data.upperContinuousForce || !data.lowerPeakForce || !data.upperPeakForce || !data.coolingMethods || !data.coreType) {
    return {
      success: false,
      message: '筛选数据不能为空'
    }
  }
  

  const { lowerContinuousForce, upperContinuousForce, lowerPeakForce, upperPeakForce, coolingMethods, coreType } = data;
  // 转成数字
  const lowerContinuousForceNum = Number(lowerContinuousForce);
  const upperContinuousForceNum = Number(upperContinuousForce);
  const lowerPeakForceNum = Number(lowerPeakForce);
  const upperPeakForceNum = Number(upperPeakForce);

  console.log("-----------")
  console.log(lowerContinuousForceNum, upperContinuousForceNum)
  console.log(lowerPeakForceNum, upperPeakForceNum)
  console.log("-----------")

  const query = db.collection('motor_type').where({
    "continuous_thrust_100c": db.command.gte(lowerContinuousForceNum).and(db.command.lte(upperContinuousForceNum)),
    "peak_thrust": db.command.gte(lowerPeakForceNum).and(db.command.lte(upperPeakForceNum)),
    "cooling_method": db.command.in(coolingMethods),
    "motor_type": coreType
  })
  const result = await query.get();
  return {
    success: true,
    message: '筛选成功',
    data: result.data
  }
}

/**
 * 获取用户的选型历史记录
 */
async function getCalculationHistory(data, wxContext) {
  try {
    const currentUser = wxContext.OPENID

    // 查询该用户的所有计算记录，按创建时间倒序排列，限制返回10条
    const queryResult = await db.collection('motor_calc_history')
      .where({
        openid: currentUser
      })
      .orderBy('createTime', 'desc')
      .limit(10)
      .get()

    return {
      success: true,
      message: '获取选型历史成功',
      data: queryResult.data || []
    }

  } catch (error) {
    console.error('获取选型历史失败:', error)
    return {
      success: false,
      message: error.message || '服务器内部错误',
      data: []
    }
  }
}

/**
 * 清空用户的选型历史记录
 */
async function clearCalculationHistory(data, wxContext) {
  try {
    const currentUser = data?.openid || wxContext.OPENID

    // 删除该用户的所有计算记录
    const deleteResult = await db.collection('motor_calc_history')
      .where({
        openid: currentUser
      })
      .remove()

    return {
      success: true,
      message: `成功删除 ${deleteResult.stats.removed} 条选型历史记录`,
      deletedCount: deleteResult.stats.removed
    }

  } catch (error) {
    console.error('清空选型历史失败:', error)
    return {
      success: false,
      message: error.message || '服务器内部错误'
    }
  }
}

/**
 * 删除单个计算记录
 */
async function deleteCalculation(data, wxContext) {
  try {
    // 数据验证
    if (!data || !data.recordId) {
      throw new Error('记录ID不能为空')
    }

    // 首先查询记录是否存在，并验证权限
    const queryResult = await db.collection('motor_calc_history')
      .doc(data.recordId)
      .get()

    if (!queryResult.data) {
      throw new Error('记录不存在')
    }

    // 验证用户权限（只有记录创建者才能删除）
    const currentUser = data.openid || wxContext.OPENID
    if (queryResult.data.openid !== currentUser) {
      throw new Error('没有权限删除此记录')
    }

    // 删除记录
    const deleteResult = await db.collection('motor_calc_history')
      .doc(data.recordId)
      .remove()

    return {
      success: true,
      message: '删除记录成功',
      recordId: data.recordId
    }

  } catch (error) {
    console.error('删除记录失败:', error)
    return {
      success: false,
      message: error.message || '服务器内部错误'
    }
  }
}

